package oss

import (
	"fmt"
	"go-learn/go_learn/prometheus/web_hook/global"
	"go-learn/go_learn/prometheus/web_hook/util"
	"strings"

	"go-learn/go_learn/prometheus/web_hook/pkg/setting"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/grand"
)

type ossClient struct {
	client *oss.Client
	config *setting.Oss
}

func NewOss(config *setting.Oss) (res *ossClient, err error) {
	client, err := oss.New(config.Endpoint, config.AccessKeyID, config.AccessKeySecret, oss.SecurityToken(""))
	if err != nil {
		return nil, err
	}

	return &ossClient{
		client: client,
		config: config,
	}, nil
}

func (o *ossClient) PutObjectWithUrl(urlTmp string) (string, error) {
	bucket, err := o.client.Bucket(o.config.Bucket)
	if err != nil {
		return "", err
	}

	storagePath := global.Prometheus.StoragePath + util.GetNowDate() + "/" + grand.Letters(16) + ".png"
	objectName := storagePath

	contents := g.Client().GetContent(urlTmp)
	err = bucket.PutObject(objectName, strings.NewReader(contents))
	signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 86400)
	if err != nil {
		return "", err
	}

	fmt.Println(signedURL)

	return signedURL, nil
}

func getSecurityToken(config *setting.Oss) (*sts.AssumeRoleResponse, error) {
	client, err := sts.NewClientWithAccessKey(config.Region, config.AccessKeyID, config.AccessKeySecret)
	if err != nil {
		return nil, err
	}

	// 构建请求对象。
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"

	// 设置参数。关于参数含义和设置方法，请参见《API参考》。
	request.RoleArn = config.RoleArn
	request.RoleSessionName = "SessionTest"

	// 发起请求，并得到响应。
	response, err := client.AssumeRole(request)
	if err != nil {
		return nil, err
	}

	return response, nil
}
